/*

[Main Script]

Project: EcoHosting - Responsive HTML5 Hosting and WHMCS Template
Version: 2.1
Author : themelooks.com

*/
$.extend($.validator.messages, {
    required: "必选字段",
    remote: "请修正该字段",
    email: "请输入正确格式的电子邮件",
    url: "请输入合法的网址",
    date: "请输入合法的日期",
    dateISO: "请输入合法的日期 (ISO).",
    number: "请输入合法的数字",
    digits: "只能输入整数",
    creditcard: "请输入合法的信用卡号",
    equalTo: "请再次输入相同的值",
    accept: "请输入拥有合法后缀名的字符串",
    maxlength: $.validator.format("请输入一个长度最多是 {0} 的字符串"),
    minlength: $.validator.format("请输入一个长度最少是 {0} 的字符串"),
    rangelength: $.validator.format("请输入一个长度介于 {0} 和 {1} 之间的字符串"),
    range: $.validator.format("请输入一个介于 {0} 和 {1} 之间的值"),
    max: $.validator.format("请输入一个最大为 {0} 的值"),
    min: $.validator.format("请输入一个最小为 {0} 的值")
});
(function ($) {
    'use strict';
    
    $(document).ready(function () {
        /* ------------------------------------------------------------------------- *
         * CUSTOM BACKGROUND IMAGE
         * ------------------------------------------------------------------------- */
        var bgSrc = $('[data-bg-src]');
        
        bgSrc.each(function () {
            var $this = $(this),
                imgValue = $this.data('bg-src');
            $this.css('background-image', 'url(' + imgValue + ')');
        });
        
        /* ------------------------------------------------------------------------- *
         * FIXED MENU
         * ------------------------------------------------------------------------- */
        var wn = $(window)
        ,   $menuTopbar = $('.menu--topbar')
        ,   primaryMenu = $('#primaryMenu')
        ,   secondaryMenu = $('#secondaryMenu')
        ,   menuHalfHeight = $menuTopbar.outerHeight() + primaryMenu.outerHeight()
        ,   menuTotalHeight = menuHalfHeight + secondaryMenu.outerHeight()
        ,   secondaryMenuToggle = function () {
                return wn.scrollTop() > menuHalfHeight ? secondaryMenu.addClass('sticky') : secondaryMenu.removeClass('sticky');
            };
        
        if ( secondaryMenu.length ) {
            secondaryMenuToggle();
            
            wn.on('resize', function () {
                menuHalfHeight = $menuTopbar.outerHeight() + primaryMenu.outerHeight();
                $headerAdjust.css('margin-top', menuTotalHeight);
            });
        }
        
        /* ------------------------------------------------------------------------- *
         * HEADER ADJUST
         * ------------------------------------------------------------------------- */
        var $headerAdjust = $('.HeaderAdjust');
        
        if ( $headerAdjust.length ) {
            $headerAdjust.css('margin-top', menuTotalHeight);
            
            wn.on('resize', function () {
                menuTotalHeight = menuHalfHeight + secondaryMenu.outerHeight();
                $headerAdjust.css('margin-top', menuTotalHeight);
            });
        }
        
        /* ------------------------------------------------------------------------- *
         * BACK TO TOP BUTTON
         * ------------------------------------------------------------------------- */
        var $backToTopBtn = $('#backToTop'),
            $domainOffer = $('.domain--offer'),
            showBackToTopBtn = function () {
                return wn.scrollTop() > 1 ? $backToTopBtn.add($domainOffer).addClass('show') : $backToTopBtn.add($domainOffer).removeClass('show');
            };
        
        $backToTopBtn.on('click', function () {
            $('html, body').animate({
                scrollTop: 0
            }, 500);
            
            return false;
        });
        
        if ( $backToTopBtn.length ) {
            showBackToTopBtn();
        }
        
        /* ------------------------------------------------------------------------- *
         * ON SCROLL
         * ------------------------------------------------------------------------- */
        wn.on('scroll', function () {
            /* TOGGLE SECONDARY MENU */
            if ( secondaryMenu.length ) {
                secondaryMenuToggle();
            }
            
            /* SHOW BACK TO TOP BUTTON */
            if ( $backToTopBtn.length ) {
                showBackToTopBtn();
            }
        });
        
        /* -------------------------------------------------------------------------*
         * FORM VALIDATION
         * -------------------------------------------------------------------------*/
        var subscribeForm = $('#subscribeForm');
        if ( subscribeForm.length ) {
            subscribeForm.validate({
                rules: {
                    EMAIL: {
                        required: true,
                        email: true
                    }
                },
                errorPlacement: function (error, element) {
                    return true;
                }
            });
        }

        //登录验证
        var loginForm = $('#loginForm');
        
        if ( loginForm.length ) {
            loginForm.validate({
                rules: {
                    email: "required",
                    password: "required"
                },
                messages: {
                    email: "邮箱地址",
                    code: "验证码",
                    name: "名字",
                    password: {
                        required: "请输入密码",
                        minlength: "密码长度不能小于 6 个",
                        equalTo: "#password"
                    },
                    confirm_password: {
                        required: "请输入密码",
                        minlength: "密码长度不能小于 6 个",
                        equalTo: "两次密码输入不一致"
                    },
                    buy_password: "交易密码",
                    password_confirmation: "确认密码",

                },

                //自定义错误消息放到哪里
                errorPlacement : function(error, element) {
                    element.next().remove();//删除显示图标
                    element.after('<span class="help-block" aria-hidden="true"></span>');
                    element.closest('.form-group').append(error);//显示错误消息提示
                },
                //给未通过验证的元素进行处理
                highlight : function(element) {
                    $(element).closest('.form-group').addClass('has-error has-feedback');
                },
                //验证通过的处理
                success : function(label) {
                    var el=label.closest('.form-group').find("input");
                    el.next().remove();//与errorPlacement相似
                    el.after('<span class="help-block" aria-hidden="true"></span>');
                    label.closest('.form-group').removeClass('has-error').addClass("has-feedback has-success");
                    label.remove();
                },
            });
        }

        var loginRegist = $('#registForm');

        if ( loginRegist.length ) {
            loginRegist.validate({
                errorElement : 'span',
                errorClass : 'help-block',
                rules: {
                    name: "required",
                    email: "required",
                    code: "required",
                    buy_password: "required",
                    password : {
                        required : true,

                        minlength : 6
                    },
                    confirm_password : {
                        required : true,

                        equalTo : "#password"
                    },
                },
                messages: {
                    email: "邮箱地址",
                    code: "验证码",
                    name: "名字",
                    password: {
                        required: "请输入密码",
                        minlength: "密码长度不能小于 6 个",
                        equalTo: "#password"
                    },
                    confirm_password: {
                        required: "请输入密码",
                        minlength: "密码长度不能小于 6 个",
                        equalTo: "两次密码输入不一致"
                    },
                    buy_password: "交易密码",
                    password_confirmation: "确认密码",

                },

                //自定义错误消息放到哪里
                errorPlacement : function(error, element) {
                    element.next().remove();//删除显示图标
                    element.after('<span class="help-block" aria-hidden="true"></span>');
                    element.closest('.form-group').append(error);//显示错误消息提示
                },
                //给未通过验证的元素进行处理
                highlight : function(element) {
                    $(element).closest('.form-group').addClass('has-error has-feedback');
                },
                //验证通过的处理
                success : function(label) {
                    var el=label.closest('.form-group').find("input");
                    el.next().remove();//与errorPlacement相似
                    el.after('<span class="help-block" aria-hidden="true"></span>');
                    label.closest('.form-group').removeClass('has-error').addClass("has-feedback has-success");
                    label.remove();
                },
            });
        }
        
        var contactForm = $('#contactForm')
        ,   contactFormStatus = $('.contact-form-status');
        
        if ( contactForm.length ) {
            contactForm.validate({
                rules: {
                    contactName: "required",
                    contactEmail: {
                        required: true,
                        email: true
                    },
                    contactSubject: "required",
                    contactMessage: "required"
                },
                errorPlacement: function (error, element) {
                    return true;
                },
                submitHandler: function(e) {
                    var formData = contactForm.serialize(); // serialize the form data

                    /* Submit the form using AJAX */
                    $.ajax({
                        type: 'POST',
                        url: contactForm.attr('action'),
                        data: formData
                    }).done(function(response) {
                        contactFormStatus.show().html(response).delay(1000).fadeOut("slow");
                    });
                }
            });
        }
        
        var postCommentForm = $('#postCommentForm');
        
        if ( postCommentForm.length ) {
            postCommentForm.validate({
                rules: {
                    name: "required",
                    email: {
                        required: true,
                        email: true
                    },
                    comments: "required"
                },
                errorPlacement: function (error, element) {
                    return true;
                }
            });
        }
        
        /* -------------------------------------------------------------------------*
         * TOOLTIP
         * -------------------------------------------------------------------------*/
        var $tooltip = $('[data-toggle="tooltip"]');
        
        if ( $tooltip.length ) {
            $tooltip.tooltip();
        }
        
        /* -------------------------------------------------------------------------*
         * OWL CAROUSEL
         * -------------------------------------------------------------------------*/
        var headerSlider = $('.header-slider'),
            headerSliderNav = $('.header--slider-nav');
        
        if ( headerSlider.length ) {
            headerSlider.owlCarousel({
                slideSpeed: 700,
                singleItem: true,
                autoPlay: true,
                addClassActive: true,
                pagination: false,
                navigation: true,
                navigationText: ['<i class="fa fa-long-arrow-left"></i>', '<i class="fa fa-long-arrow-right"></i>'],
                afterMove: function () {
                    headerSliderNav.find('li').removeClass('active').eq(this.currentItem).addClass('active');
                }
            });
        }
        
        headerSliderNav.on('click', 'li', function () {
            headerSlider.trigger('owl.goTo', $(this).index());
        });
        
        var testimonialSlider = $('.testimonial-slider')
        ,   testimonialCustomPagination = function () {
                $.each(this.owl.userItems, function (i) {
                    var recommenderThumb = jQuery(this).data('recommender-thumb');
                    var paginationLinks = jQuery('.testimonial-slider .owl-page span');

                    $(paginationLinks[i]).html('<img src="'+ recommenderThumb +'" alt="" class="img-responsive" />');
                });
            };
            
        if ( testimonialSlider.length ) {
            if (testimonialSlider.children('.testimonial-item').length > 3) {
                testimonialSlider.addClass('overload');
            }
            testimonialSlider.owlCarousel({
                slideSpeed: 700,
                paginationSpeed: 700,
                singleItem: true,
                autoPlay: true,
                addClassActive: true,
                afterInit: testimonialCustomPagination,
                afterUpdate: testimonialCustomPagination
            });
        }
        
        var brandsSlider = $('.brands-slider');
            
        if ( brandsSlider.length ) {
            brandsSlider.owlCarousel({
                slideSpeed: 700,
                paginationSpeed: 700,
                items: 5,
                autoPlay: true,
                pagination: false
            });
        }

        /* ------------------------------------------------------------------------- *
         * VPS SLIDER
         * ------------------------------------------------------------------------- */
        var $headerVPS = $('.vps-pricing--slider-holder')
        ,   vpsSlider = $('.VPSPricingSlider')
        ,   vpsItemCPUel = $('.vps-pricing--cpu')
        ,   vpsItemRAMel = $('.vps-pricing--ram')
        ,   vpsItemSPACEel = $('.vps-pricing--space')
        ,   vpsItemBANDWIDTHel = $('.vps-pricing--bandwidth')
        ,   vpsItemPriceEl = $('.vps-pricing--total-price span')
        ,   inputCPUText = $('.InputCPUText')
        ,   inputRamText = $('.InputRamText')
        ,   inputSpaceText = $('.InputSpaceText')
        ,   inputBandwidthText = $('.InputBandwidthText')
        ,   inputPriceText = $('.InputPriceText')
        ,   vpsPricingBtn = $('.vps-pricing--action-btn .btn');
        
        if ( vpsSlider.length ) {
            // VPS slider variables
            var $uiSliderHandle,
                maxPlans = vpsSliderOpts.maxPlans - 1,
                detfaultPlan = vpsSliderOpts.detfaultPlan - 1;
            
            // Add slider pips
            for ( var i = 0; i < maxPlans; i++ ) {
                $('<div class="pip"></div>')
                    .css('left', ((100 / maxPlans) * i) + '%')
                    .appendTo( $headerVPS.children('.pips') );
            }
            
            // Initialize slider
            vpsSlider.slider({
                animate: "fast",
                range: "min",
                min: 0,
                max: maxPlans,
                value: detfaultPlan,
                step: 1,
                create: function () {
                    vpsItemCPUel.text(vpsSliderOpts.plans[detfaultPlan].cpuText);
                    vpsItemRAMel.text(vpsSliderOpts.plans[detfaultPlan].ramText);
                    vpsItemSPACEel.text(vpsSliderOpts.plans[detfaultPlan].spaceText);
                    vpsItemBANDWIDTHel.text(vpsSliderOpts.plans[detfaultPlan].brandwidthText);
                    vpsItemPriceEl.text(vpsSliderOpts.plans[detfaultPlan].priceText);
                    vpsPricingBtn.attr('href', vpsSliderOpts.plans[detfaultPlan].url);
                    
                    inputCPUText.val(vpsSliderOpts.plans[detfaultPlan].cpuText);
                    inputRamText.val(vpsSliderOpts.plans[detfaultPlan].ramText);
                    inputSpaceText.val(vpsSliderOpts.plans[detfaultPlan].spaceText);
                    inputBandwidthText.val(vpsSliderOpts.plans[detfaultPlan].brandwidthText);
                    inputPriceText.val(vpsSliderOpts.plans[detfaultPlan].priceText);
                    
                    $uiSliderHandle = vpsSlider.children('.ui-slider-handle');
                    $('<i class="fa fa-map-marker"></i><em></em>').appendTo($uiSliderHandle);
                    $uiSliderHandle.children('em').html(vpsSliderOpts.plans[detfaultPlan].planName);
                },
                slide: function (event, ui) {
                    vpsItemCPUel.text(vpsSliderOpts.plans[ui.value].cpuText);
                    vpsItemRAMel.text(vpsSliderOpts.plans[ui.value].ramText);
                    vpsItemSPACEel.text(vpsSliderOpts.plans[ui.value].spaceText);
                    vpsItemBANDWIDTHel.text(vpsSliderOpts.plans[ui.value].brandwidthText);
                    vpsItemPriceEl.text(vpsSliderOpts.plans[ui.value].priceText);
                    vpsPricingBtn.attr('href', vpsSliderOpts.plans[ui.value].url);
                    
                    inputCPUText.val(vpsSliderOpts.plans[ui.value].cpuText);
                    inputRamText.val(vpsSliderOpts.plans[ui.value].ramText);
                    inputSpaceText.val(vpsSliderOpts.plans[ui.value].spaceText);
                    inputBandwidthText.val(vpsSliderOpts.plans[ui.value].brandwidthText);
                    inputPriceText.val(vpsSliderOpts.plans[ui.value].priceText);
                    
                    $uiSliderHandle.children('em').html(vpsSliderOpts.plans[ui.value].planName);
                }
            });
        }
        
        /* -------------------------------------------------------------------------*
         * COUNTER
         * -------------------------------------------------------------------------*/
        var counterNum = $('.counter-number');
            
        if ( $(counterNum).length ) {
            $(counterNum).counterUp({
                delay: 10,
                time: 1000
            });
        }
        
        /* -------------------------------------------------------------------------*
         * MAP
         * -------------------------------------------------------------------------*/

        
        /* -------------------------------------------------------------------------*
         * PRICING TABLE LABEL
         * -------------------------------------------------------------------------*/
        if ( wn.width() < 992 ) {
            $('#compare table td, #pricingTable2 table td').each(function () {
                $(this).prepend('<span class="labelText">'+ $(this).data('label') + '</span>');
            });
        }
        
        /* ------------------------------------------------------------------------- *
         * TWITTER WIDGET
         * ------------------------------------------------------------------------- */
        var $sidebarTwitter = $('#sidebarTwitter');

        if ( $sidebarTwitter.length ) {
            twttr.widgets.createTimeline({
                sourceType: "profile",
                screenName: $sidebarTwitter.data('user-name')
            }, document.getElementById('sidebarTwitter'));
        }
        



    });
    
    $(window).on('load', function () {
        /* ------------------------------------------------------------------------- *
         * PRELOADER
         * ------------------------------------------------------------------------- */
        var $preloader = $('#preloader');
        
        if ( $preloader.length ) {
            $preloader.fadeOut('slow');
        }
    });
})(jQuery);
